package com.xiong.common.config;



import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.*;


import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/6 0:02
 * @since JDK 1.8
 *
 * 访问地址 127.0.0.1:8085/doc.html
 */
@Slf4j
@Configuration
@EnableSwagger2 // 启用swagger2
public class SwaggerConfig implements ApplicationContextAware {

    ApplicationContext applicationContext ;


    @org.springframework.context.annotation.Bean
    public Docket createRestApi() {
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<>();
        parameterBuilder.name("Authorization").description("令牌").modelRef(new ModelRef("string")).parameterType("header")
              .required(false).build();
       parameters.add(parameterBuilder.build());

        Map<String, Object> map = this.applicationContext.getBeansWithAnnotation(SwaggerScan.class);

        List<String> strings=new ArrayList<>();
        for(Map.Entry<String,Object> obj : map.entrySet()){
            log.info(obj.getKey() );
            strings.add(obj.getKey());
        }

        System.out.println(JSONObject.toJSONString(strings));

        return new Docket(DocumentationType.SPRING_WEB)
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage(strings))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameters);

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    private static Predicate<RequestHandler> basePackage(List<String> strings) {
        return input -> declaringClass(input).transform(handlerPackage(strings)).or(true);
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

    private static Function<Class<?>, Boolean> handlerPackage(List<String> strings)     {
        return input -> {
            // 循环判断匹配
            for (int i = 0; i < strings.size() ; i++) {
                String str=strings.get(i);
                boolean isMatch = input.getPackage().getName().startsWith(str);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot")
                .description("swagger-bootstrap-ui")
                .termsOfServiceUrl("http://localhost:8085/")
                .contact("2532223478@mail.com")
                .version("1.0")
                .build();
    }
}
